package com.adong.test.subclass;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @author adong
 */
public class SubClassTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void init() {
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
    }

    @After
    public void destroy() {
        transaction.commit();
        session.close();
        sessionFactory.close();
    }

    /**
     * 1.对于子类对象只需要把记录插入到一张数据表中
     * 2.辨别者列有Hibernate自动维护
     */
    @Test
    public void SaveTest() {
        Person person = new Person();
        person.setAge(19);
        person.setName("adong");
        session.save(person);

        Student student = new Student();
        student.setAge(200);
        student.setName("波波");
        student.setSchool("清华大学");
        session.save(student);
    }

    /**
     * 查询数据只需要查询一张数据表
     * 对于子类记录,也只需要查询一张数据表
     * 缺点：
     * 使用了辨别者列，子类独有的字段不能添加非空元素，继承层次较深，表中字段也比较多
     */
    @Test
    public void testQuery() {
        List persons = session.createQuery("FROM Person").list();
        System.out.println(persons.size());
        List student = session.createQuery("FROM Student").list();
        System.out.println(student.size());
    }
}
